﻿using System;
using System.Collections.Generic;
using System.Data.SqlServerCe;
using System.Drawing;
using System.Linq;
using System.Text;
using KBS8.Shared;

namespace KBS8.Data.GdfDataFilter
{
    class ComplexFeatureReader : DatabaseReader
    {
        private string _query;

        public ComplexFeatureReader(SqlCeConnection connection)
            : base(connection)
        {
            
        }

        /// <summary>
        /// Reads the ComplexFeatures in the database
        /// </summary>
        /// <param name="o"></param>
        public override void Read(FilteredOutput o)
        {
            _query =
                "SELECT ComplexFeatureId, FeatureDefenitionId, ToComplexFeatureId, FromComplexFeatureId, MaxX, MinX, MaxY, MinY " +
                "FROM ComplexFeature " +
                "WHERE (" + o.Area.X + " < MaxX) AND " +
                "(MinX < " + (o.Area.X + o.Area.rec.Width) +") AND " +
                "(" + o.Area.Y + " < MaxY) AND " +
                "(MinY < " + o.Area.Y + o.Area.rec.Height + ")";

            try
            {
                Connection.Open();

                SqlCeCommand command = Connection.CreateCommand();
                command.CommandText = _query;

                SqlCeDataReader reader = command.ExecuteReader();

                while (reader.Read())
                {
                    ComplexFeature complexFeature = new ComplexFeature
                        {
                            ComplexId = Convert.ToInt32(reader["ComplexFeatureId"]),
                            FeatureId = Convert.ToInt32(reader["FeatureDefenitionId"]),
                            ToComplex = Convert.ToInt32(reader["ToComplexFeatureId"]),
                            FromComplex = Convert.ToInt32(reader["FromComplexFeatureId"]),
                            MaxX = Convert.ToInt32(reader["MaxX"]),
                            MinX = Convert.ToInt32(reader["MinX"]),
                            MaxY = Convert.ToInt32(reader["MaxY"]),
                            MinY = Convert.ToInt32(reader["MinY"])
                        };
                    o.ComplexFeatures.Add(complexFeature);
                }
                reader.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine("ComplexFeatureReader.cs: " + e.Message);
            }
            finally
            {
                Connection.Close();
            }
        }
    }
}